package client

import (
	"context"
	"google.golang.org/grpc"
	"self/common/proto/user"
)

type Handler func(ctx context.Context, in user.UserClient) (interface{}, error)

func UserClient(ctx context.Context, handler Handler) (interface{}, error) {
	dial, err := grpc.Dial("127.0.0.1:9991", grpc.WithInsecure())
	if err != nil {
		return nil, err
	}
	client := user.NewUserClient(dial)
	res, err := handler(ctx, client)
	if err != nil {
		return nil, err
	}
	return res, nil
}
func Login(ctx context.Context, i *user.RegisterReq) (*user.RegisterResp, error) {
	client, err := UserClient(ctx, func(ctx context.Context, in user.UserClient) (interface{}, error) {
		login, err := in.Register(ctx, i)
		if err != nil {
			return nil, err
		}
		return login, err
	})
	if err != nil {
		return nil, err
	}
	return client.(*user.RegisterResp), err
}
func UserList(ctx context.Context, i *user.UserListReq) (*user.UserListResp, error) {
	client, err := UserClient(ctx, func(ctx context.Context, in user.UserClient) (interface{}, error) {
		list, err := in.UserList(ctx, i)
		if err != nil {
			return nil, err
		}
		return list, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*user.UserListResp), nil
}
